package com.hoo.auth;

import java.io.Serializable;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springside.modules.utils.Encodes;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.SimplePrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.ByteSource;
import org.apache.shiro.web.subject.support.WebDelegatingSubject;
import javax.annotation.PostConstruct;
import com.hoo.entity.account.Resource;
import com.hoo.entity.account.Users;
import com.hoo.exception.LockedAccountException;
import com.hoo.service.account.AccountService;
import com.hoo.service.account.PermissionService;
import com.hoo.exception.CaptchaWrongException;

public class MyRealm extends AuthorizingRealm {

	@Autowired
	private AccountService accountService;
	
	@Autowired
	private PermissionService permissionService;

	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(
			PrincipalCollection principals) {
		UserContext userContext = (UserContext) getAvailablePrincipal(principals);
		Users user = accountService.getUserByLoginName(userContext.getLoginName());
		if (user != null) {
			SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
			authorizationInfo.addRole(user.getRoleId() + "");
			List<Resource> resources = permissionService.getResourcesByRoleId(user.getRoleId());
			for (Resource resource : resources) {
				authorizationInfo.addStringPermission(resource.getHref());
			}
			return authorizationInfo;
		}
		return null;
	}

	/**
	 * 验证当前登录的Subject
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(
			AuthenticationToken authcToken) throws AuthenticationException {
		UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
		WebDelegatingSubject subject = (WebDelegatingSubject) SecurityUtils.getSubject();
		Session session = subject.getSession();
		String code = (String) session.getAttribute(ValidateCodeServlet.VALIDATE_CODE);
		if (StringUtils.isBlank(token.getCaptcha())
				|| !token.getCaptcha().toUpperCase().equals(code)) {
			throw new CaptchaWrongException("验证码错误.");
		}
		Users user = accountService.getUserByLoginName(token.getUsername());
		if (user != null) {
			 if (user.getUserFlag() == 0) { 
				 throw new LockedAccountException("用户被锁定."); 
			 }
			byte[] salt = Encodes.decodeHex(user.getSalt());
			return new SimpleAuthenticationInfo(new UserContext(user), user.getLoginPassword(), ByteSource.Util.bytes(salt), getName());
		} else {
			return null;
		}
	}

	/**
	 * 设定Password校验的Hash算法与迭代次数.
	 */
	@PostConstruct
	public void initCredentialsMatcher() {
		HashedCredentialsMatcher matcher = new HashedCredentialsMatcher(
				AccountService.HASH_ALGORITHM);
		matcher.setHashIterations(AccountService.HASH_INTERATIONS);
		setCredentialsMatcher(matcher);
	}

	/**
	 * 清空用户关联权限认证，待下次使用时重新加载
	 */
	public void clearCachedAuthorizationInfo(String principal) {
		SimplePrincipalCollection principals = new SimplePrincipalCollection(
				principal, getName());
		clearCachedAuthorizationInfo(principals);
	}

	/**
	 * 清空所有关联认证
	 */
	public void clearAllCachedAuthorizationInfo() {
		Cache<Object, AuthorizationInfo> cache = getAuthorizationCache();
		if (cache != null) {
			for (Object key : cache.keys()) {
				cache.remove(key);
			}
		}
	}

	/**
	 * 授权用户信息
	 */

	public static class UserContext implements Serializable {
		private static final long serialVersionUID = 1L;
		private Integer id;
		private String loginName;
		private String usercode;
		private String realName;
		private Integer roleId;
		private Users user;
		private Map<String, Object> cacheMap;
		private Integer parentUserId;
		private String parentUsercode;

		public UserContext(Users user) {
			this.id = user.getId();
			this.loginName = user.getLoginName();
			this.roleId = user.getRoleId();
			this.user = user;
		}

		public Map<String, Object> getCacheMap() {
			if (cacheMap == null) {
				cacheMap = new HashMap<String, Object>();
			}
			return cacheMap;
		}

		
		public Users getUser() {
			return user;
		}

		public void setUser(Users user) {
			this.user = user;
		}

		public Integer getId() {
			return id;
		}

		public void setId(Integer id) {
			this.id = id;
		}

		public String getLoginName() {
			return loginName;
		}

		public void setLoginName(String loginName) {
			this.loginName = loginName;
		}

		public String getUsercode() {
			return usercode;
		}

		public void setUsercode(String usercode) {
			this.usercode = usercode;
		}

		public String getRealName() {
			return realName;
		}

		public void setRealName(String realName) {
			this.realName = realName;
		}

		public Integer getRoleId() {
			return roleId;
		}

		public void setRoleId(Integer roleId) {
			this.roleId = roleId;
		}

		public Integer getParentUserId() {
			return parentUserId;
		}

		public void setParentUserId(Integer parentUserId) {
			this.parentUserId = parentUserId;
		}

		public String getParentUsercode() {
			return parentUsercode;
		}

		public void setParentUsercode(String parentUsercode) {
			this.parentUsercode = parentUsercode;
		}

		public static long getSerialversionuid() {
			return serialVersionUID;
		}

		public void setCacheMap(Map<String, Object> cacheMap) {
			this.cacheMap = cacheMap;
		}

	}

	/**
	 * 将一些数据放到ShiroSession中,以便于其它地方使用
	 * 
	 * @see 比如Controller,使用时直接用HttpSession.getAttribute(key)就可以取到
	 */
	private void setSession(Object key, Object value) {
		Subject currentUser = SecurityUtils.getSubject();
		if (null != currentUser) {
			Session session = currentUser.getSession();
			System.out.println("Session默认超时时间为[" + session.getTimeout() + "]毫秒");
			if (null != session) {
				session.setAttribute(key, value);
			}
		}
	}
}
